package com.example.controller;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.Util.WechatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = "认证接口")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WechatUtil wechatUtil;

    @ApiOperation("微信登录")
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, Object> loginData) {
        Map<String, Object> result = new HashMap<>();

        try {
            String code = (String) loginData.get("code");
            Map<String, Object> userInfo = (Map<String, Object>) loginData.get("userInfo");

            // 1. 使用code调用微信接口获取openid
            Map<String, String> wechatResult = wechatUtil.getOpenid(code);
            String openid = wechatResult.get("openid");

            if (openid == null || openid.isEmpty()) {
                result.put("code", 401);
                result.put("msg", "获取openid失败");
                return result;
            }

            // 2. 登录/注册逻辑
            String token = userService.wechatLogin(openid);
            log.info("Toekn为: {}", token);

            // 3. 更新用户信息
            if (userInfo != null) {
                String nickname = (String) userInfo.get("nickName");
                String avatar = (String) userInfo.get("avatarUrl");
                userService.updateUserInfoByOpenid(openid, nickname, avatar);
            }

            // 4. 返回token和用户信息
            User user = userMapper.selectByOpenid(openid);
            result.put("code", 200);
            result.put("msg", "登录成功");
            result.put("token", token);

            // 返回前端需要的用户信息
            Map<String, Object> userData = new HashMap<>();
            userData.put("nickName", user.getNickname());
            userData.put("avatarUrl", user.getAvatar());
            result.put("userInfo", userData);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "登录失败: " + e.getMessage());
        }

        return result;
    }
}